import { createRouter, createWebHashHistory } from 'vue-router'
import useStore from '@/store'
import Layout from '@/views/layout/index.vue'
import Home from '@/views/home/index.vue' // 首页不惜要懒加载
import NotFound from '@/views/404.vue'

const routes = [
  {
    path: '/teset',
    component: () => import('@/views/teset/index.vue')
  },
  {
    path: '/login',
    component: () => import('@/views/login/index.vue')
  },
  {
    path: '/login/callback',
    component: () => import('@/views/login/components/login-callback.vue')
  },
  {
    path: '/404',
    component: NotFound
  },
  {
    path: '/',
    component: Layout,
    children: [
      {
        path: '',
        component: Home
      },
      {
        path: '/category/:id',
        component: () => import('@/views/category/index.vue')
      },
      {
        path: '/category/sub/:id',
        component: () => import('@/views/category/sub.vue')
      },
      {
        path: '/goods/:id',
        component: () => import('@/views/goods/index.vue')
      },
      {
        path: '/cart',
        component: () => import('@/views/cart/index.vue')
      },
      {
        path: '/member/checkout',
        component: () => import('@/views/member/pay/checkout.vue')
      },
      {
        path: '/member/pay/:id',
        component: () => import('@/views/member/pay/index.vue')
      },
      {
        path: '/pay/callback',
        component: () => import('@/views/member/pay/callback.vue')
      },
      {
        path: '/member',
        component: () => import('@/views/member/layout/index.vue'),
        children: [
          {
            path: '',
            component: () => import('@/views/member/home/index.vue')
          },
          {
            path: 'order',
            component: () => import('@/views/member/order/index.vue')
          }
        ]
      }
    ]
  }

  // {
  //   path: '*',
  //   redirect: '/404'
  // }
]

const router = createRouter({
  history: createWebHashHistory(), //哈希模式
  routes,
  // 跳转, 滚动条到最顶端
  scrollBehavior: () => ({ top: 0 })
})

// 前置守卫
router.beforeEach((to, from, next) => {
  // 没得信息去登录页
  const { cart } = useStore()
  if (cart.isLogin) {
    next()
  } else {
    // console.log(to.path)
    if (to.path.includes('member'))
      return next({
        path: '/login',
        query: { name: to.fullPath }
      })
    next()
  }
})

export default router
